package javabase.thinkinjava.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

import static javabase.thinkinjava.nio.GetChannel.BSIZE;

/**
 * @author fance
 * @date 18-4-30 上午8:29
 */
public class BufferToText {
    public static void main(String[] args) throws IOException {
        FileChannel fileChannel = new FileOutputStream("data.txt").getChannel();
        fileChannel.write(ByteBuffer.wrap("some txt".getBytes()));
        fileChannel.close();

        fileChannel = new FileInputStream("data.txt").getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
        fileChannel.read(buffer);
        buffer.flip();
        System.out.println(buffer.asCharBuffer());
        buffer.rewind();
        String encoding = System.getProperty("file.encoding");
        System.out.println("decoded using " + encoding + ": "
        + Charset.forName(encoding).decode(buffer));

        fileChannel = new FileOutputStream("data.txt").getChannel();
        fileChannel.write(ByteBuffer.wrap("some text".getBytes("UTF-16BE")));
        fileChannel.close();

        fileChannel = new FileInputStream("data.txt").getChannel();
        buffer.clear();
        fileChannel.read(buffer);
        buffer.flip();
        System.out.println(buffer.asCharBuffer());

        fileChannel = new FileOutputStream("data.txt").getChannel();
       buffer = ByteBuffer.allocate(24);
       buffer.asCharBuffer().put("some text");
       fileChannel.write(buffer);
       fileChannel.close();

        fileChannel = new FileInputStream("data.txt").getChannel();
        buffer.clear();
        fileChannel.read(buffer);
        buffer.flip();
        System.out.println(buffer.asCharBuffer());
    }
}
